LeetCode Js-58. Length of Last Word
Given a string s consisting of words and spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
給予一個有文字與空格的s字串,回傳最後字串的文字長度。
單字是由非空格組成之字串
Example 1:
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
Solution:
word = [a, b, c]
array 0 1 2
Code:
var lengthOfLastWord = function(s) {
const arr = s.trim().split(' ')
return arr[arr.length - 1].length
};
FlowChart:
Example 1
step.1
string 1 2
arr = ['Hello', 'World']
array 0 1
arr.length = 2
return arr[arr.length - 1].length
//arr[1].length => 'World'.length => 5